const Koa = require('koa')
const static = require('koa-static')
const koaBody = require('koa-body')
const fs = require('fs')
const router = require('koa-route')
const path = require('path')


const app = new Koa()

// 上传文件
const upload = async(ctx,next)=>{
    // 获取文件
    const files = ctx.request.files.file;
    for(let file of files){
        // 创建可读流
        // file.path 文件在服务器本地的地址
        const reader = fs.createReadStream(file.path)
        let filePath = path.join(__dirname,'public/upload/') + `${file.name}`
        // 创建可写流
        const upStream = fs.createWriteStream(filePath)
        // 可读流通过管道写入可写流
        reader.pipe(upStream)
    }   
    return ctx.response.body = '上传成功'
}


app.use(static(
    __dirname
))
app.use(koaBody({
    multipart:true,
    formidable:{
        maxFileSize:2*1024*1024
    }
}))
app.use(router.post('/uploadfile',upload))
app.listen(80,()=>{
    console.log('80')
})